import React from 'react';
import { Modal } from 'antd';
import CubeMap from './pages/map';
// import FileDownload from './pages/FileDownload';
import window from './util';
import { WeaLocaleProvider,WeaTools,WeaInputLocale } from "ecCom";
const WindowFunc = WeaTools.WindowFunc;
const getLabel = WeaLocaleProvider.getLabel;

const showModal = (title, content, width: number = 600) => {
    Modal.success({
        title: <span><div className='wea-browser-single-icon-circle' style={{ background: "#96358a" }}><i className='icon-coms-ModelingEngine' /></div>{title}</span>,
        content: content,
        iconType: "",
        okText: getLabel(309, "关闭"),
        width: width,
        onOk() {  },
    });
}


window.cubeshowDdImg=(fieldids,w,h,isbatch,isdownload,docs,formmode_authorizeUrl)=>{
    playImg(window.event,fieldids,isdownload,formmode_authorizeUrl);
}
const playImg = (e,fieldid,isdownload,formmode_authorizeUrl) => {     // 图片轮播
    const jq = getCurrentJQuery();
    const currentWindow = getCurrentWindow();
    const imgPool:any = [];
    let indexNum = 0;
    const fieldids = fieldid.split(',');
    fieldids.map(item=>{
        imgPool.push(`${"/weaver/weaver.file.FileDownload?fileid="+item+formmode_authorizeUrl}`);
    })
    for (let i = 0; i < imgPool.length; i++) {
        if (jq(e.target).attr('data-imgsrc') === imgPool[i]) {
            break;
        } else {
            indexNum++;
        }
    }   
    window.IMCarousel.showImgScanner4Pool(true, imgPool, indexNum, null, currentWindow.top);
}
const getCurrentJQuery = () => {
    const currentWindow = getCurrentWindow();
    return currentWindow.$ || currentWindow.jQuery;
}
// 获取 window
const getCurrentWindow = () => {
    return WindowFunc.getParent() !== window ? WindowFunc.getTop()
    : window;
}

export default {
    createBARCode: (id, text, customId, modeId, formId) => {
        showModal(text, (
            <div style={{ textAlign: 'center', minHeight: 60 }}>
                <img src={`/weaver/weaver.formmode.servelt.BARcodeBuildAction?modeid=${modeId}&formid=${formId}&billid=${id}&customid=${customId}&randomnum=${new Date().getTime()}`} />
            </div>
        ));
    },
    createQRCode: (id, text, customId, modeId, formId) => {
        showModal(text, (
            <div style={{ textAlign: 'center', minHeight: 60 }}>
                <img src={`/weaver/weaver.formmode.servelt.QRcodeBuildAction?modeid=${modeId}&formid=${formId}&billid=${id}&customid=${customId}&randomnum=${new Date().getTime()}`} />
            </div>
        ));
    },
    viewLog: (billid, text, modeId, _) => {
        window.modeopenFullWindowHaveBar(`/spa/cube/index.html#/main/cube/logList?modeId=${modeId}&billid=${billid}&modename=${text}`)
    },
    toEdit: (billid, _, modeId, formId) => {
        window.modeopenFullWindowHaveBar(`/spa/cube/index.html#/main/cube/card?type=2&modeId=${modeId}&formId=${formId}&billid=${billid}`)
    },
    doprint: (billid, _, modeId, formId) => {
        window.modeopenFullWindowHaveBar(`/spa/cube/index.html#/main/cube/card?type=4&modeId=${modeId}&formId=${formId}&billid=${billid}`)
    },
    showFormModeMap: (fieldvalue) => {
        showModal(getLabel(82639, '地图'), (
            <div style={{ height: 450, margin: "-30px -50px" }}>
                <CubeMap titles={fieldvalue} />
            </div>
        ), 700);
    },
    expCard:(billid, _, modeId, formId)=>{
        window.open(`/weaver/weaver.formmode.excel.ExpCardExcelServer?modeId=${modeId}&formId=${formId}&action=expcard&billid=${billid}`);
    }
}

export const generateUUID = () => {
    var d = new Date().getTime();
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
    return uuid;
};

export const formatMultLang=(...args)=>{
    if(args.length==0){
        return '';
    }else if(args.length==1){
        return args[0];
    }else{
        let str=args[0];
        for(let i=1;i<args.length;i++){
            str=str.replace('{'+(i-1)+'}',args[i]);
        }
        return str;
    }
}

export const decodeMultiLang=(value)=>{  
    if(!value){
        return "";
    }
    if(value&&typeof value=='string'&&value.startsWith('base64_')){
        value=value.substring(7);
        return WeaTools.Base64.decode(value);
    }else if(value&&typeof value=='string'&&value.startsWith('~`~`')&&value.endsWith('`~`~')){
        const languageidweaver=window.localStorage.getItem('languageidweaver')||'7';
        let v='';
        WeaInputLocale.getList(value, function(list) {
          Object.keys(list).map(item => {
              if(item.trim()==languageidweaver){
                v=list[item];
              }
          })
          return v;
        })
        return v;
    }else{
        return value;
    }
}


//代码块中<script id>标签转换处理
export const manageScriptContent = (content) =>{
    if(!content)
        return "";
    //script标签存在自定义属性的，生成个空span兼容
    const reg = new RegExp("<script .*?id=.*?></script>|<script .*?id=.*?/>", "ig");
    const arr = content.match(reg);
    let appendScriptSpan = "";
    arr && arr.map(v =>{
        appendScriptSpan += v.replace(new RegExp("(<|/)script","ig"), "$1span");
    });
    //document.write覆写Dom结构兼容
    content = content.replace(/document.write/g, 'jQuery("#scriptArea").append');
    //剔除html头等信息
    content = content.replace(/<(\/?)(html|body|head)>/ig, "");
    //剔除部分JS文件引入导致异常
    const scriptSrcArr = [
        "/wui/common/jquery/plugin/Listener_wev8.js",
        "/js/workflow/VCEventHandle_wev8.js"
    ];
    scriptSrcArr.forEach(item =>{
        content = content.replace(new RegExp("<script .*?"+item+".*?></script>|<script .*?"+item+".*?/>","ig"), "");
    });
    return content + appendScriptSpan;
}